import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import WPT from 'wpt';
import showhide from '@wpt/showHide';
import moveElement from 'modules/moveElement';
import S from './index.m.less';

@showhide
export default class BackTop extends PureComponent {
    static defaultProps = {
        showTopScreenNum: 2,
        beforeToTop: null,
        className: '',
        onChange: () => undefined,
        visible: true,
    };

    static propTypes = {
        showTopScreenNum: PropTypes.number,
        beforeToTop: PropTypes.func,
        className: PropTypes.any,
        onChange: PropTypes.func,
        visible: PropTypes.bool,
    }

    state = {
        showTop: false, // 展示到顶部按钮
    };

    componentDidMount() {
        this.onPageShow();
    }

    componentWillUnmount() {
        this.onPageHide();
    }

    onPageShow = () => {
        window.setTimeout(() => {
            WPT.scroll.appendScroll(this.key, top => {
                const showTop = top > window.screen.availHeight * this.props.showTopScreenNum;
                this.props.onChange && this.props.onChange(showTop);
                this.setState({
                    showTop,
                });
            });
        }, 2000);

        this.destroyMove = this.createMove();
    };

    onPageHide = () => {
        WPT.scroll.clear(this.key);
        this.destroyMove && this.destroyMove.destroy();
    };

    key = `${Math.random() * 100}${WPT.nowTime}`;

    $ref = React.createRef();

    createMove = () => (this.$ref.current && moveElement(this.$ref.current, ({ moveY, target }) => {
        target.style.top = `${moveY}px`;
    }))

    backTop = e => {
        e.preventDefault();
        e.stopPropagation();
        this.props.beforeToTop && this.props.beforeToTop();
        WPT.Util.animateScroll(0).then(() => {
            this.props.onChange && this.props.onChange(false);
            this.setState({
                showTop: false, // 置顶并隐藏按钮
            });
        });
    };

    render() {
        const { showTop } = this.state;
        const { className, visible } = this.props;

        return visible && (
            <div
                ref={this.$ref}
                className={cx(S.backTop, showTop && S.show, className)}
                onClick={this.backTop}
            />
        );
    }
}
